package com.UBC417.termproject.Data;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.appengine.api.datastore.*;
import com.google.appengine.api.datastore.Query.SortDirection;

@SuppressWarnings("deprecation")
public class User {

	public static boolean Signup(String userName, String userId, String password, String type){
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
		
		Key k = KeyFactory.createKey(User.class.getSimpleName(), userId);
		
		try {
	        ds.get(k);
	    } catch (EntityNotFoundException e){
	        Entity user = new Entity("User", userId);
			user.setProperty("userName", userName);
			Date date = new Date();
			user.setProperty("date", date);
			user.setProperty("userId", userId);
			user.setProperty("password", password);
			user.setProperty("type", type);
			ds.put(user);
			return true;
	    }
		return false;
		
	}
	
	public static Boolean Signin(String userId, String password){
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();

		Query query = new Query("User").addFilter("userId", Query.FilterOperator.EQUAL, userId);
		Iterable<Entity> users = ds.prepare(query).asIterable();
		for (Entity e : users){
			if (e.getProperty("password").equals(password)){
				return true;
			}
		}
		return false;
	}
	
	public static void Unsubscribe(String userId, String password){
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
		
		Query query = new Query("User").addFilter("userId", Query.FilterOperator.EQUAL, userId);
		Iterable<Entity> users = ds.prepare(query).asIterable();
		for (Entity e : users){
			if (e.getProperty("password").equals(password)){
				//remove entity
				ds.delete(e.getKey());
			}
		}
		
		Seller.CloseInactiveUserAuction(userId);
		Buyer.CloseInactiveUserBid(userId);
	}
	
	
	public static String getUserType(String userId){
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();

		Query query = new Query("User").addFilter("userId", Query.FilterOperator.EQUAL, userId);
		Iterable<Entity> users = ds.prepare(query).asIterable();
		String type="";
		for (Entity e : users){
			type=(String) e.getProperty("type");
		}
		return type;
	}
	
	public static List<Bid> MonitorAuction(String auctionId){
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();

		// sort bids by price from high to low
		Query query = new Query("Bid").addFilter("auctionId", Query.FilterOperator.EQUAL, auctionId).addSort("price",SortDirection.DESCENDING);
		Iterable<Entity> entities = ds.prepare(query).asIterable();
		List<Bid> items = new ArrayList<Bid>();
		for (Entity e : entities){
			 Bid b = new Bid();
			 b.setAuctionId((String)e.getProperty("auctionId"));
			 b.setDateCreated((Date)e.getProperty("dateCreated"));
			 b.setPrice((Double)e.getProperty("price"));
			 b.setUserId((String)e.getProperty("userId"));
			 b.setItemName((String)e.getProperty("itemName"));
			 items.add(b);
		}
		return items;
	}
	
	public static Auction getAuctionInfo(String auctionId) throws EntityNotFoundException{
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
		
		Key k = KeyFactory.stringToKey(auctionId);
	    Entity e= ds.get(k);
	    Auction a= new Auction();
	    a.setName((String)e.getProperty("name"));
		a.setUserId((String)e.getProperty("userId"));
		a.setStartTime((Date)e.getProperty("startDate"));
		a.setEndTime((Date)e.getProperty("endDate"));
		a.setStatus((String)e.getProperty("status"));
		a.setId(KeyFactory.keyToString(e.getKey()));
		return a;
	}
	
	public static Bid getHighestBid(String auctionId){
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();

		// sort bids by price from high to low
		Query query = new Query("Bid").addFilter("auctionId", Query.FilterOperator.EQUAL, auctionId).addSort("price",SortDirection.DESCENDING);
		Iterable<Entity> entities = ds.prepare(query).asList(FetchOptions.Builder.withLimit(1));
		Bid b = new Bid();
		for (Entity e : entities){	 
			 b.setAuctionId((String)e.getProperty("auctionId"));
			 b.setDateCreated((Date)e.getProperty("dateCreated"));
			 b.setPrice((Double)e.getProperty("price"));
			 b.setUserId((String)e.getProperty("userId"));
			 b.setItemName((String)e.getProperty("itemName"));
		}

		return b;
	}
	
	public static String getHighestBidUser(String auctionId){
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();

		// sort bids by price from high to low
		Query query = new Query("Bid").addFilter("auctionId", Query.FilterOperator.EQUAL, auctionId).addSort("price",SortDirection.DESCENDING);
		Iterable<Entity> entities = ds.prepare(query).asList(FetchOptions.Builder.withLimit(1));
		String b = null;
		for (Entity e : entities){	 
			 b = ((String)e.getProperty("userId"));
		}

		return b;
	}
	
	public static String IsAuctionWinner(String buyerId, String auctionId){
		String bestBidId = getHighestBidUser(auctionId);
		Boolean active = Buyer.IsBidActive(auctionId);
		Boolean cancel = Buyer.IsBidCancelled(auctionId);
		Boolean unsubed = Buyer.IsBidUserUnsub(auctionId);
		
		if (cancel || unsubed)
			return "-";
		if (bestBidId.equals(buyerId)){
			if (active)
				return "WINNING";
			else
				return "WON";
		}
		else{
			if (active)
				return "LOSING";
			else
				return "LOST";
		}
	}
	
	public static Item getAuctionItem(String auctionId){
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();

		// sort bids by price from high to low
		Query query = new Query("Item").addFilter("auctionId", Query.FilterOperator.EQUAL, auctionId);
		Iterable<Entity> entities = ds.prepare(query).asIterable();
		Item i= new Item();
		for(Entity e : entities){
			
			i.setAuctionId((String)e.getProperty("auctionId"));
			i.setBasePrice((Double)e.getProperty("basePrice"));
			i.setDescription((String)e.getProperty("description"));
			i.setName((String)e.getProperty("name"));
			i.setStatus((String)e.getProperty("status"));
			
		}
		return i;
	}
	
	public static void updateAuction(){
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
		Date now = new Date();
		Query query = new Query("Auction").addFilter("endDate", Query.FilterOperator.LESS_THAN, now);
		Iterable<Entity> entries = ds.prepare(query).asIterable();	
		List<Entity> todo = new ArrayList<Entity>();
		for(Entity e : entries) {
			String auctionId = KeyFactory.keyToString(e.getKey());
			query = new Query("Item").addFilter("auctionId", Query.FilterOperator.EQUAL, auctionId);
			Iterable<Entity> entries2 = ds.prepare(query).asIterable();
			for(Entity e2 : entries2){
				e.setProperty("status", "Closed");
				e2.setProperty("status", "Closed");
				todo.add(e);
				todo.add(e2);				
			}			
		}
		ds.put(todo);
		
	}

}
